import dayjs from "dayjs";
import { Ref, computed } from "vue";
import { cancelBatchOrderShipmentApi, geBusinesstListApi, getBusinessPageStaticApi, statisticsDataApi } from "@/api/waybillManagement/businessWaybill/index";
import { cancelMergeDeclarationApi, customsClearanceApi, shipmentBoxVolumeExcelListApi, syncTrackApi } from "@/api/waybillManagement/customerServiceWaybill";
import { listByBusinessIdApi } from "@/api/waybillManagement/businessWaybill";
import CommonHook from "@/hook/commonHook";
import { message as Message } from "ant-design-vue";
import printJs from "print-js";
import { printLabelApi } from "@/api/common";
export default function OperationHook(state: {
  searchForm: BusinessWaybill.SearchForm;
  tableData: Ref<Array<BusinessWaybill.ListRows>>;
  drawerOpts: Base.DrawerOpts;
  dialogOpts: Base.DialogOpts;
  loading: Ref<boolean>;
  tableRef: any;
  saPageInfo: Base.GeneraDataType;
  pageStat: Ref<Base.GeneraDataType>;
  activeKey: Ref<string>;
}) {
  const { searchForm, tableData, drawerOpts, loading, tableRef, saPageInfo, dialogOpts, pageStat, activeKey } = state;
  const selectRows = computed<Array<ClientWaybillManagement.ListRows>>(() => {
    return tableRef.value.xTable.getCheckboxRecords() || [];
  });
  const { downloadFileByBlob } = CommonHook();
  const getData = async () => {
    const params = {
      ...getParams(),
      saPageInfo: saPageInfo.value
    };
    loading.value = true;
    return geBusinesstListApi(params)
      .then((res: any) => {
        const { code, data } = res;
        if (code === 200) {
          tableData.value = data.records || [];
          searchForm.total = Number(data.total);
          saPageInfo.value = data.saPageInfo || {};
        }
      })
      .finally(() => {
        loading.value = false;
      });
  };
  const pageStateic = () => {
    const params = getParams();
    loading.value = true;

    return getBusinessPageStaticApi({ ...params, statusList: [5, 6, 7, 8, 9, -5, 0, -2] })
      .then((res: any) => {
        const { code, data } = res;
        if (code === 200) {
          Object.assign(pageStat.value, {
            5: data[5],
            6: data[6],
            7: data[7],
            8: data[8],
            9: data[9],
            "-5": data[-5],
            0: data[0],
            "-2": data[-2]
          });
          // activeKey.value = String(getNoZeroKey(pageStat.value, ["5", "6", "7", "8", "9", "-5", "0", "-2"]));
        }
      })
      .finally(() => {
        loading.value = false;
      });
  };
  const getParams = () => {
    const {
      keyWordsList,
      waybillNumList,
      fbaNumberList,
      transferOrderNumberList,
      bizIdList,
      followIdList,
      channelIdList,
      markList,
      notMark,
      customerIdList,
      makeInvoiceStatus,
      warehousePropertyList,
      zipCode,
      countryRegionIdList,
      customsTaxesTypeList,
      customsDeclarationType,
      innerRemark,
      status,
      remark,
      depositTime,
      createdTime,
      warehouseCodeList,
      pageNum,
      pageSize,
      companyIds,
      warehouseNames,
      outWarehouseTime,
      outWarehouseBrokerIds
    } = searchForm;
    const params: any = {
      waybillNumList: [],
      keyWordsList: [],
      fbaNumberList: [],
      transferOrderNumberList: [],
      bizIdList,
      followIdList,
      channelIdList,
      warehouseCodeList,
      remark,
      markList,
      notMark,
      customerIdList,
      makeInvoiceStatus,
      warehousePropertyList,
      zipCode,
      countryRegionIdList,
      customsTaxesTypeList,
      customsDeclarationType,
      innerRemark,
      status,
      startTime: createdTime.length ? dayjs(createdTime[0]).format("YYYY-MM-DD HH:mm:ss") : undefined,
      endTime: createdTime.length ? dayjs(createdTime[1]).format("YYYY-MM-DD HH:mm:ss") : undefined,
      depositStartTime: depositTime.length ? dayjs(depositTime[0]).format("YYYY-MM-DD HH:mm:ss") : undefined,
      depositEndTime: depositTime.length ? dayjs(depositTime[1]).format("YYYY-MM-DD HH:mm:ss") : undefined,
      pageNum,
      pageSize,
      companyIds,
      warehouseNames,
      outWarehouseStartTime: outWarehouseTime.length ? dayjs(outWarehouseTime[0]).format("YYYY-MM-DD HH:mm:ss") : undefined,
      outWarehouseEndTime: outWarehouseTime.length ? dayjs(outWarehouseTime[1]).format("YYYY-MM-DD HH:mm:ss") : undefined,
      outWarehouseBrokerIds,
      statusList: [Number(activeKey.value)]
    };
    if (waybillNumList)
      params.waybillNumList = waybillNumList
        .trim()
        .replace(/,{1,}|，{1,}|\+{1,}|\s{1,}/g, ",")
        .split(",");
    if (keyWordsList)
      params.keyWordsList = keyWordsList
        .trim()
        .replace(/,{1,}|，{1,}|\+{1,}|\s{1,}/g, ",")
        .split(",");
    if (fbaNumberList)
      params.fbaNumberList = fbaNumberList
        .trim()
        .replace(/,{1,}|，{1,}|\+{1,}|\s{1,}/g, ",")
        .split(",");
    if (transferOrderNumberList)
      params.transferOrderNumberList = transferOrderNumberList
        .trim()
        .replace(/,{1,}|，{1,}|\+{1,}|\s{1,}/g, ",")
        .split(",");
    if (channelIdList.length) {
      params.channelIdList = channelIdList.map((t: any) => t[t.length - 1]);
    }
    if (searchForm.sort) {
      params.order = searchForm.order;
      params.sort = searchForm.sort;
    }

    return params;
  };
  const searchHandle = async () => {
    searchForm.pageNum = 1;
    await pageStateic();
    getData();
  };
  const changeTabHandle = () => {
    getData();
  };
  const showHandle = (row: ClientWaybillManagement.ListRows) => {
    drawerOpts.title = `查看(${row.waybillNum})`;
    drawerOpts.width = "1200px";
    drawerOpts.type = 1;
    drawerOpts.component = "Details";
    drawerOpts.passData = row;
    drawerOpts.visible = true;
  };
  // 修改渠道
  const modifyChannelHandle = () => {
    if (!selectRows.value.length) return Message.error("请勾选运单!");
    if (selectRows.value.length > 1) return Message.error("只能勾选1条运单!");
    dialogOpts.title = `修改渠道`;
    dialogOpts.width = "520px";
    dialogOpts.type = 1;
    dialogOpts.component = "ModifyChannel";
    dialogOpts.passData = selectRows.value[0];
    dialogOpts.visible = true;
  };
  // 修改品名
  const modifyProductNameHandle = () => {
    if (!selectRows.value.length) return Message.error("请勾选运单!");
    if (selectRows.value.length > 1) return Message.error("只能勾选1条运单!");
    if (selectRows.value[0].makeInvoiceStatus === -2) return Message.error("当前运单已制作发票、请修改运单发票装箱详情内产品中文名！");
    dialogOpts.title = `修改品名`;
    dialogOpts.width = "520px";
    dialogOpts.type = 1;
    dialogOpts.component = "ModifyProductName";
    dialogOpts.passData = selectRows.value[0];
    dialogOpts.visible = true;
  };
  // 修改材质
  const modifyMasterialHandle = () => {
    if (!selectRows.value.length) return Message.error("请勾选运单!");
    if (selectRows.value.length > 1) return Message.error("只能勾选1条运单!");
    if (selectRows.value[0].makeInvoiceStatus === -2) return Message.error("当前运单已制作发票、请修改运单发票装箱详情内材质！");
    dialogOpts.title = `修改材质`;
    dialogOpts.width = "520px";
    dialogOpts.type = 1;
    dialogOpts.component = "ModifyMasterial";
    dialogOpts.passData = selectRows.value[0];
    dialogOpts.visible = true;
  };
  // 修改客户备注
  const modifyRemarkHandle = () => {
    if (!selectRows.value.length) return Message.error("请勾选运单!");
    dialogOpts.title = `修改客户备注`;
    dialogOpts.width = "520px";
    dialogOpts.type = 1;
    dialogOpts.component = "ModifyRemark";
    dialogOpts.passData = selectRows.value;
    dialogOpts.visible = true;
  };
  // 修改客户备注
  const modifyInnerRemarkHandle = () => {
    if (!selectRows.value.length) return Message.error("请勾选运单!");
    dialogOpts.title = `修改内部备注`;
    dialogOpts.width = "520px";
    dialogOpts.type = 2;
    dialogOpts.component = "ModifyRemark";
    dialogOpts.passData = selectRows.value;
    dialogOpts.visible = true;
  };

  // 取消运单
  const cancelShipmentHandle = () => {
    if (!selectRows.value.length) return Message.error("请勾选运单!");
    const ids = selectRows.value.map((t: any) => t.id);

    cancelBatchOrderShipmentApi(ids).then((res: any) => {
      const { code, data } = res;
      if (code === 200 && data === "取消成功") {
        Message.success("操作成功!");
        getData();
        pageStateic();
      }
    });
  };

  // 使用模版导出
  const templateExportHandle = () => {
    dialogOpts.title = `模版导出`;
    dialogOpts.width = "520px";
    dialogOpts.component = "TemplateExport";
    dialogOpts.type = Number(activeKey.value);
    dialogOpts.passData = { searchForm: getParams(), selectRows: selectRows.value };
    dialogOpts.visible = true;
  };
  // 自定义模版导出
  const customExportHandle = () => {
    dialogOpts.title = `自定义模版导出`;
    dialogOpts.width = "800px";
    dialogOpts.component = "CustomExport";
    dialogOpts.type = Number(activeKey.value);
    dialogOpts.passData = { searchForm: getParams(), selectRows: selectRows.value };
    dialogOpts.visible = true;
  };

  // 获取统计数据
  const getStatisticsDataFn = () => {
    const params: any = {
      ...getParams(),
      // statusList: [Number(activeKey.value)],
      saPageInfo: saPageInfo.value
    };
    if (selectRows.value.length) params.idList = selectRows.value.map((t: CustomerServiceWaybill.ListRows) => t.id);
    return statisticsDataApi(params).then((res: any) => {
      const { code, data } = res;
      if (code === 200) {
        dialogOpts.passData = data || {};
      }
    });
  };
  // 查看统计
  const showStatictisHandle = () => {
    dialogOpts.title = "查看统计";
    dialogOpts.width = "900px";
    dialogOpts.component = "DataStatistics";
    dialogOpts.visible = true;
  };
  //制作发票
  const makeInvoiceHandle = () => {
    if (!selectRows.value.length) return Message.error("请勾选运单!");
    if (selectRows.value.length > 1) return Message.error("只能勾选1条运单!");
    if (selectRows.value[0].makeInvoiceStatus === -2) return Message.error("只能操作未制作发票的数据!");
    drawerOpts.title = `制作发票`;
    drawerOpts.width = "1800px";
    drawerOpts.type = 1;
    drawerOpts.component = "MakeInvoice";
    drawerOpts.passData = selectRows.value[0];
    drawerOpts.visible = true;
  };
  // 打印
  const printLabelHandle = () => {
    if (!selectRows.value.length) return Message.error("请勾选运单!");
    loading.value = true;
    printLabelApi({ idList: selectRows.value.map((t: ClientAdvanceManagement.ListRows) => t.id), type: 2 })
      .then((res: any) => {
        if (res.headers["content-type"] === "application/json") {
          const reader = new FileReader(); //创建一个FileReader实例
          reader.readAsText(res.data, "utf-8"); //读取文件,结果用字符串形式表示
          reader.onload = () => {
            //读取完成后,**获取reader.result**
            const { message } = JSON.parse(reader.result as string);
            Message.error(message); //弹出错误提示
          };
        } else {
          const pdfUrl = window.URL.createObjectURL(res.data);
          printJs({ printable: pdfUrl, type: "pdf" });
        }
      })
      .finally(() => (loading.value = false));
  };
  // 下载标签
  const downloadLabelHandle = (buttonType: number | undefined) => {
    if (!selectRows.value.length) return Message.error("请勾选运单!");
    loading.value = true;
    printLabelApi({ idList: selectRows.value.map((t: ClientAdvanceManagement.ListRows) => t.id), type: 2, buttonType })
      .then((res: any) => {
        if (res.headers["content-type"] === "application/json") {
          const reader = new FileReader(); //创建一个FileReader实例
          reader.readAsText(res.data, "utf-8"); //读取文件,结果用字符串形式表示
          reader.onload = () => {
            //读取完成后,**获取reader.result**
            const { message } = JSON.parse(reader.result as string);
            Message.error(message); //弹出错误提示
          };
        } else {
          //判断推单状态
          if (res.headers["content-type"] === "application/pdf") {
            const { waybillNum, channelName, itemNumber } = selectRows.value[0];
            downloadFileByBlob(res.data, `${waybillNum}+${itemNumber}件+${channelName}.pdf`, "application/pdf");
          } else {
            downloadFileByBlob(res.data, "标签.zip");
          }
        }
      })
      .finally(() => (loading.value = false));
  };
  //日志
  const showLogHandle = (row: WarehouseEntryChannel.ListRows) => {
    drawerOpts.title = "日志";
    drawerOpts.width = "1200px";
    drawerOpts.passData = row;
    drawerOpts.component = "OperationLog";
    drawerOpts.type = 2;
    drawerOpts.visible = true;
  };

  const requestFn = () => {
    return listByBusinessIdApi({ businessId: drawerOpts.passData?.id, sysModule: "运单管理" });
  };
  // 发票导出
  const invoiceExportHandle = () => {
    if (!selectRows.value.length) return Message.error("请勾选运单!");
    const index = selectRows.value.findIndex((t: BusinessWaybill.ListRows) => t.makeInvoiceStatus === -1);
    if (index !== -1) return Message.error("只能勾选已制作发票的运单!");
    dialogOpts.title = "发票导出";
    dialogOpts.width = "520px";
    dialogOpts.passData = selectRows.value;
    dialogOpts.component = "InvoiceExport";
    dialogOpts.visible = true;
  };
  //材积明细导出
  const VolumeExportHandle = () => {
    if (!selectRows.value.length) return Message.error("请勾选运单!");
    loading.value = true;
    return shipmentBoxVolumeExcelListApi(selectRows.value.map((t: any) => t.id))
      .then((res: any) => {
        const { filename } = res.headers;
        const name = filename.split(".");
        name && name.length && downloadFileByBlob(res.data, `材积明细.${name[1]}`);
      })
      .finally(() => {
        loading.value = false;
      });
  };

  //合并报关
  const customsClearanceHandle = () => {
    if (selectRows.value.length < 2) return Message.error("至少勾选两条运单!");
    loading.value = true;
    return customsClearanceApi(selectRows.value.map((t: any) => t.id))
      .then((res: any) => {
        const { code } = res;
        if (code === 200) {
          Message.success("操作成功!");
          searchHandle();
        }
      })
      .finally(() => {
        loading.value = false;
      });
  };

  //取消合并报关
  const cancelMergeDeclarationHandle = () => {
    if (!selectRows.value.length) return Message.error("请勾选运单!");
    loading.value = true;
    return cancelMergeDeclarationApi(selectRows.value.map((t: any) => t.id))
      .then((res: any) => {
        const { code } = res;
        if (code === 200) {
          Message.success("操作成功!");
          searchHandle();
        }
      })
      .finally(() => {
        loading.value = false;
      });
  };

  //更新运踪
  const updateTrackHandle = () => {
    if (!selectRows.value.length) return Message.error("请勾选运单!");
    if (selectRows.value.length > 100) return Message.error("一次勾选最多100条!");

    return syncTrackApi({ idList: selectRows.value.map((t: any) => t.id) }).then((res: any) => {
      console.log(res);
      const { code, data } = res;
      if (code === 200) {
        Message.success(data);
        getData();
      }
    });
  };
  //问题件
  const addProblemShipment = () => {
    if (!selectRows.value.length) return Message.error("请勾选运单!");
    if (selectRows.value.length > 1) return Message.error("一次勾选最多1条!");
    if (selectRows.value[0].status === 0) return Message.error("取消的运单不可发起问题件!");

    drawerOpts.title = `发起问题件`;
    drawerOpts.width = "1200px";
    drawerOpts.type = 1;
    drawerOpts.component = "ProblemShipment";
    drawerOpts.passData = selectRows.value[0];
    drawerOpts.visible = true;
  };

  return {
    searchHandle,
    getData,
    showHandle,
    changeTabHandle,
    modifyChannelHandle,
    modifyMasterialHandle,
    modifyProductNameHandle,
    modifyRemarkHandle,
    modifyInnerRemarkHandle,
    cancelShipmentHandle,
    templateExportHandle,
    customExportHandle,
    getStatisticsDataFn,
    showStatictisHandle,
    makeInvoiceHandle,
    printLabelHandle,
    downloadLabelHandle,
    showLogHandle,
    requestFn,
    invoiceExportHandle,
    VolumeExportHandle,
    customsClearanceHandle,
    cancelMergeDeclarationHandle,
    updateTrackHandle,
    addProblemShipment
  };
}
